const serialport = require("serialport");

class SerialPort {
  constructor(dev = "/dev/rfcomm0", option = { baudRate: 9600 }) {
    this.name = dev
    this.device = new serialport(dev, option)
    this.device.on('open', () => {
      console.log('open ', dev, 'success')
    })

    this.device.on('close', () => {
      console.log('串口连接已关闭');
    });

    this.device.on('error', (err) => {
      console.error('SerialPort error: ', err.message);
    });

  }

  writeAndDrain(data, callback) {
    this.device.write(data, (error) => {
      if (error) {
        console.log(error)
        callback()
      } else {
        this.device.drain(callback);
      }
    });
  }

  static listDevices() {
    return serialport.list()
  }

  readString(count) {
    var buf
    if (count > 0) {
      buf = this.device.read(count)
    } else {
      buf = this.device.read()
    }
    if (buf)
      return buf.toString()
    else {
      return ''
    }
  }
  read(count) {
    var buf
    if (count > 0) {
      buf = this.device.read(count)
    } else {
      buf = this.device.read()
    }
    if (buf)
      return buf
    else {
      return []
    }
  }
  clearFlush() {
    try {
      if (this.device.isOpen) {
        this.device.flush((err) => {
          if (err) {
            console.error('Error flushing serial port:', err);
          } else {
            this.device.read();
            console.log('Serial port flushed');
          }
        });
      }
    } catch (error) {
      console.log(error)
    }
  }
  close() {
    try {
      if (this.device.isOpen)
        this.device.close()
      console.log('Serial port closed:', this.name);
    } catch (error) {
      console.log(error)
    }
  }

}

module.exports = SerialPort

/*
function callbackFun(){
  console.log('22222')
}

const sp = new SerialPort()
sp.writeAndDrain('12345',callbackFun)
*/

SerialPort.listDevices().then(console.log)